<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\Admin\PermissionDeniedException;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Gate,Auth,Log;
use App\Http\Requests\Admin\AccountBooks\AccountBooksRequest;
use App\Services\AccountBooks;

use App\Models\Goods;
use App\Models\GoodsStockHistory;
use App\Models\GoodsEorderInfo;
use App\Services\Openssl\AccountBooksException;
use App\Interfaces\GoodsStockHistoryService;



class AccountBooksController extends Controller
{
    public function account_books_gate()
    {
        if (!Gate::allows('goods','')) {
            throw new PermissionDeniedException();
        }//end if()

    }

    /**
     * 默认页面
     *
     * @date 2016/03/08
     * @author Leen
     */
    public function index(Request $request){

        $this->account_books_gate();

        $search = array('brand_id'=>0,'goods_name'=>'');

        $account_books = '';

        return view('admin.account_books.index',compact(['account_books', 'search']));

    }//end func index()

    public function create(){

    }


	/**
	 * 添加
	 *
     * @date 2016/03/08
     * @author Leen
	 */
    public function store(AccountBooksRequest $accountBooksRequest, AccountBooks $accountBooks, GoodsStockHistoryService $goodsStockHistoryService)
    {

        $this->account_books_gate();

        $return = ['status'=>1, 'message'=>'', 'data'=>''];
        $dcrTimes = $accountBooksRequest->dcrTimes;             //比对次数
        $date = $accountBooksRequest->date;

        if(empty($dcrTimes)){

            $return['status'] = 0;
            $return['message'] = "次数不能为空";

        }//end if()

        $dcrTimes = intval($dcrTimes);
        if(gettype($dcrTimes) != 'integer'){

            $return['status'] = 0;
            $return['message'] = "次数不能为空";
        }

        if(empty($date)){

            $return['status'] = 0;
            $return['message'] = "月份不能为空";
        }//end if()

        //$dates = '2016/02';
        $date = str_replace( '/', '-' , $date);


        $year = substr($date, 0, 4);
        $month = substr($date, 5, 2);


        $start_time = mktime(0, 0 , 0,$month,2,$year);
        //$end_time = mktime(23,59,59,$month,date("t"),$year);
        $end_time = mktime(23,59,59,$month+1,1,$year);


//1、根据月份的开始时间和结束时间查出库存操作记录表中该段时间内的所有商品编号（去重，groupBy），即该时间段内有库存变化的商品
//2、去除商品编号中的非e贸易商品编号，只保留e贸易商品编号
//3、根据e贸易商品编号数组查出每个商品的库存操作记录
//4、计算每个商品的该段时间内的入库数量、出库数量，以及应剩余数量、实际剩余数量和该段时间开始时间的库存数量
//5、调用账册服务，欧克

        $goods = Goods::rightJoin('goods_stock_history AS gsh', 'goods.goods_id', '=', 'gsh.goods_id')
            ->rightJoin('goods_eorder_info AS gei', 'goods.goods_sn', '=', 'gei.goods_sn')
            ->select("goods.goods_id", "goods.goods_sn", "goods.goods_name", "goods.goods_number", "gei.unitCiq", "gei.storeInfo")
            ->where('goods.type', 1)
            ->whereRaw("gsh.add_time BETWEEN ? AND ?", array($start_time, $end_time))
            ->groupBy('goods.goods_id')
            ->get();


        if($goods->count()) {

            foreach ($goods as $key => $item) {

                $goods_id = $item['goods_id'];
                $goods_sn = $item['goods_sn'];
                /*$goods_id = $item->goods_id;
                $goods_sn = $item->goods_sn;*/

                $goodsStockHistory = $goodsStockHistoryService->getByGoodsId($goods_id);
                $goods_stock = Goods::where('goods_id', $goods_id)->pluck('goods_number');

                $legalInQty = 0;           //入库数量
                $legalOutQty = 0;          //出库数量
                $legalRemainQty = 0;       //应剩余数量
                $realRemainQty = 0;        //实际剩余数量
                $periodStartQty = 0;       //期初数量
                if($goodsStockHistory->count()){

                    //存在库存操作记录
                    foreach($goodsStockHistory as $keys=>$stockHistory){
                        $number = $stockHistory['number'];
                        $stock_status = $stockHistory['stock_status'];
                        $add_time = $stockHistory['add_time'];

                        switch($stock_status){

                            case 1:

                                if($add_time >= $start_time && $add_time <= $end_time){
                                    $legalInQty += $number;
                                }//end if()

                                $legalRemainQty += $number;

                                break;

                            case 2:

                                if($add_time >= $start_time && $add_time <= $end_time){
                                    $legalOutQty += $number;
                                }//end if()

                                $legalRemainQty -= $number;
                                break;

                            case 3:

                                break;

                        }//end switch()

                    }//end if()
                }//end if()

                $goodsStockHistory = $legalRemainQty - $legalInQty + $legalOutQty; //期初数量=应剩余数量 - 本月入库数量 + 本月入库数量

                $goods[$key]['legalInQty'] = abs($legalInQty);           //入库数量
                $goods[$key]['legalOutQty'] = abs($legalOutQty);          //出库数量
                $goods[$key]['legalRemainQty'] = abs($legalRemainQty);       //应剩余数量
                $goods[$key]['realRemainQty'] = isset($goods_stock) ? $goods_stock : 0;        //实际剩余数量
                //$goods[$key]['realRemainQty'] = abs($legalRemainQty);        //实际剩余数量
                $goods[$key]['periodStartQty'] = abs($goodsStockHistory);       //期初数量
            }//end forerach()

            $goods = $goods->toArray();

            $start_date = date("Ymd",$start_time);
            $end_date = date("Ymd",$end_time);

            $result = $accountBooks->sendPost($goods, $dcrTimes, $start_date, $end_date);

            if($result){
                $return['message'] = "对账成功";
                $return['data'] = $goods;

            }else{
                $return['status'] = 0;
                $return['message'] = "对账失败";
                $return['data'] = $result;
            }//end if()

        }else{
            $return['status'] = 0;
            $return['message'] = "该月份没有可对账的商品数据";
        }//end if()

        return $return;

    }//end func store()



	/**
	 * 编辑
	 *
     * @date 2016/03/08
     * @author Leen
	 */
    public function edit($goods_id)
    {


    }//end func store()


	/**
	 * 更新
	 *
     * @date 2016/03/08
     * @author Leen
	 */
    public function update($id)
    {

    }//end func store()


	/**
	 * 删除
	 *
	 * @date 2016/03/08
	 * @author Leen
	 */
    public function destroy($id)
    {

    }//end func store()


}//end calss GoodsController
